#!/usr/bin/env python
#coding:utf-8
import socket,os,sys,commands,re
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from config import Settings

class ViewLog(object):
    def __init__(self,hostname,logtype,datetime,show_num):
        self.hostname=hostname
        self.logtype=logtype
        self.datetime=datetime
        self.show_num=show_num

    def log_show(self):
        ipaddress=socket.gethostbyname(self.hostname)
        if 'api' in self.hostname:
            log_show_cmds="ansible {} -m shell -a 'tail -{} {}{}_log-{}'"\
                .format(ipaddress,self.show_num,Settings.set_api_log_dir,self.logtype,self.datetime)
            stat, res = commands.getstatusoutput(log_show_cmds)
        elif 'web' in self.hostname:
            log_file_name='{}{}.log-{}'.format(Settings.set_web_log_dir, self.logtype, self.datetime)
            log_check_show_cmds = "ansible {ip} -m shell -a 'tail -{sn} {fn}'" \
                .format(ip=ipaddress, fn=log_file_name,sn=self.show_num)
            stat2,res2=commands.getstatusoutput(log_check_show_cmds)
            if stat2:
                log_show_cmds = "ansible {ip} -m shell -a 'gzip -d {fn}.gz && tail -{sn} {fn}'" \
                    .format(ip=ipaddress, fn=log_file_name, sn=self.show_num)
                stat, res = commands.getstatusoutput(log_show_cmds)
            else:
                res=res2
        else:
            return 'Error:主机名错误'
        if re.search('(?i)no such file',res):
            return 'Error:没有这个时间的日志'
        return res
